%%%-------------------------------------------------------------------
%%% @author admin
%%% @copyright (C) 2021, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 31. 十二月 2021 11:13
%%%-------------------------------------------------------------------
-module(pl_svr).
-author("admin").
-behaviour(gen_server).

-include("log.hrl").
-include("player.hrl").
-include("account.hrl").
-include("system_pb.hrl").

%% API
-export([init/1, handle_call/3, handle_cast/2, handle_info/2]).
-export([start/2, start_link/2]).


start(AccountId, Pid) ->
    supervisor:start_child(pl_svr_sup,[AccountId, Pid]).

start_link(AccountId, Pid) ->
    gen_server:start_link(?MODULE, [AccountId,Pid], []).

init([AccountId, Pid]) ->
    gen_server:cast(self(), init),
    {ok, [AccountId, Pid]}.

handle_call(Request, From, State) ->
    do_call(Request, From, State).

handle_cast(init, [AccountId, Pid]) ->
    try
        State = account:init(AccountId, Pid),
        erlang:put(net_pid, Pid),
        PlayerList = [#player_list{uuid = UUid, name = Name}||#player{uuid = UUid, name = Name} <- State#account.player_list],
        self() ! {route_msg, #s2c_login{state = 1, players = PlayerList}},
        {noreply, State}
    catch
        Err:Reason->
            ?ERR("ERR:~p,Reason:~p",[Err,Reason]),
            {stop, Reason, []}
    end;
handle_cast(Request, State) ->
    do_cast(Request, State).

handle_info(Request, State) ->
    do_info(Request, State).



do_call({route_evt, MsgId, Data}, _From, Account) ->
    mod_route:evt_route_call(MsgId, Data, Account);

do_call(_Msg, _, Player) ->
    ?ERR("unknow Msg call, info:~w",[_Msg]),
    {reply, error, Player}.

do_cast({route_msg, Data}, Account = #account{}) ->
    mod_route:msg_route(Data, Account);
do_cast({route_evt, MsgId, Data}, Account = #account{}) ->
    mod_route:evt_route_cast(MsgId, Data, Account);
do_cast(_Msg, Player) ->
    ?ERR("unknow Msg cast, info:~w",[_Msg]),
    {noreply, error, Player}.

do_info({route_msg, Data}, Account) ->
    mod_route:msg_route(Data, Account);
do_info({route_evt, MsgId, Data}, Account) ->
    mod_route:evt_route_cast(MsgId, Data, Account);
do_info(_Msg, Account) ->
    ?ERR("unknow Msg info, info:~w",[_Msg]),
    {noreply, error, Account}.